﻿#include "stdafx.h"
#include "AstFunction.h"
#include "AstClass.h"
#include "AstPackage.h"
#include "SiContext.h"
#include "Temporary.h"
#include "AutoType.h"
#include "FunctionInstance.h"
#include "ClassInstanceType.h"

SiContext::SiContext(SiContext * p) : parent(p)
{
	if(p)	pathName = p->pathName;
}

void SiContext::defineFunction(const std::string & name, AstFunction *f)
{
	_functions.insert(std::make_pair(name, f));
}

void SiContext::setClass(const std::string & name, AstClass * cls) {
	auto o = _class.insert(std::make_pair(name, cls));
	if (!o.second) throw std::runtime_error("类名字冲突:" + name);
}

AstClass * SiContext::findClass(const std::string & name) {
	auto i = _class.find(name);
	if (i != _class.end()) return i->second;
	if (parent) return parent->findClass(name);
	return nullptr;
}

CodeGen * SiContext::makeCall(const std::string & name, std::vector<std::pair<std::string, CodeGen*>>& arguments)
{
	auto it = _functions.equal_range(name);
	CodeGen* x = nullptr;
	for (auto i = it.first; i != it.second; i++) {
		auto *f = i->second;

		auto *p = f->makeCall(arguments);
		if (p) {
			if (x) throw std::runtime_error("多个函数匹配:" + name);
			x = p;
		}
	}
	if (x) return x;
	if (parent) return parent->makeCall(name, arguments);
	return nullptr;
}

std::string SiContext::makeNameByTypes(const std::vector<Parameter>& ordered) {
	std::string n = ":";
	for (auto i : ordered) {
		n += i.type->uniqueName() + ':';
	}
	n.pop_back();
	return n;
}


